﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IoTEdge.Grpc.Server.ABBLibs.Base;
using IoTEdge.Grpc.Server.Libs;
using IoTEdge.Grpc.Server.Libs.Base;
using IoTEdge.Grpc.Server.Libs.services;
using NLog;

namespace IoTEdge.Grpc.Server.AMR
{
    internal class BackgroundAmrCollectPlugin : BackgroundService
    {
        NLog.ILogger logger = LogManager.GetCurrentClassLogger();
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var task1 = Task.Factory.StartNew((x) =>
            {
                var cancel = (CancellationToken)x;
                logger.Info("AMR采集驱动正在运行!");
                AmrCollect collect = new CollectService();
                try
                {
                    collect.Start(cancel, RestartAmr);
                }
                catch (Exception exp)
                {
                    logger.Fatal($"AMR采集驱动出现致命错误: {exp.Message}");
                    return;
                }

            }, stoppingToken);

            await Task.WhenAll(task1);
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            await base.StartAsync(cancellationToken);
        }

        public void RestartAmr()
        {
            AmrCollect collect = new CollectService();
            logger.Warn("AMR采集驱动正在重新启动!...");
            collect.Start(CancellationToken.None, RestartAmr);
        }
    }
}